import { Router } from 'vue-router';
import { useAuthStore } from '@/stores';
import { storeToRefs } from 'pinia';
import usePermissionHook  from '@/hooks/admin/usePermissionHook';

export const setupRouterGuard = (router: Router) => {
	router.beforeEach(async (to, from, next) => {
		const { authRoutes } = storeToRefs(useAuthStore());
		const { addDynamicRoutes } = usePermissionHook();
		// 如果目标路由是登录页，直接放行
		if (to.name === 'login') {
			return next();
		}
		// 存在缓存直接放行则直接获取
		if (!authRoutes.value || authRoutes.value.length === 0) {
			return next({ name: 'login' });
		} else {
			await addDynamicRoutes(router, authRoutes.value as any);
			// 如果添加路由后当前路径仍然不匹配，则重定向
			if (!router.hasRoute(to.name!)) {
				return next({ ...to, replace: true });
			  }
		}
		
		next();
	});
};
